<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/28
 * Time: 11:41
 */

namespace app\home\controller;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Session;

class Weixin extends Controller
{
    public function index(){
//        第一步：用户同意授权，获取code
        $appid = "wx0e64e7f20a99049b";
        $url = urlencode("http://118.193.221.147/online/public/home/Weixin/getcode");//回调函数
//        urlencode()函数原理就是首先把中文字符转换为十六进制，然后在每个字符前面加一个标识符%。
//urldecode()函数与urlencode()函数原理相反，用于解码已编码的 URL 字符串，其原理就是把十六进制字符串转换为中文字符urlencode()函数原理就是首先把中文字符转换为十六进制，然后在每个字符前面加一个标识符%。
//urldecode()函数与urlencode()函数原理相反，用于解码已编码的 URL 字符串，其原理就是把十六进制字符串转换为中文字符
        $this->redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$url."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
    }

    public function getcode(){
//        dump($_GET);
        $code = $_GET['code'];
//        通过code换取网页授权access_token
        $urll = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx0e64e7f20a99049b&secret=086b2fc843046dfcacd054261ed3eb51&code=".$code."&grant_type=authorization_code";
        $access =  file_get_contents($urll);//获取uel的返回内容
        $result = json_decode($access, true);//吧json数据转换成数组
//        此时access_token只有两个小时
//        dump($result);
//        array(5) {
//            ["access_token"] => string(107) "VRYQS6OV24VYUrPtX3otk5q_oe8A_x6cIlPPNag9kQLkuMH3mA5Py-lFqDcWjQWbUg1dI2xtgK8Gsg_HQTV71ajSULz8sJcdgBUElDO2Okg"
//            ["expires_in"] => int(7200)
//            ["refresh_token"] => string(107) "vhQcE20YU5X_Tyo5x-nK0sLtxNb47pq7-Uk_o0f2rEKcwtDj0LuDN0LYw3CapJKzb3dQCaBs_ahchuayM8wgtRTT41vZER65i6B3GDfmQW8"
//            ["openid"] => string(28) "ofqgOwjr3aCvUqEgZoMVEGcPkowU"
//            ["scope"] => string(15) "snsapi_userinfo"
//}
//        第三步：刷新access_token（如果需要）换取更长时间的access_token
        $access_token = $result["refresh_token"];
        $urll2 = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=wx0e64e7f20a99049b&grant_type=refresh_token&refresh_token=".$access_token;
        $access_to =  file_get_contents($urll2);
        $results = json_decode($access_to, true);
//        dump($results);

//        array(5) {
//            ["openid"] => string(28) "ofqgOwjr3aCvUqEgZoMVEGcPkowU"
//            ["access_token"] => string(107) "AJKtWJU1PFPu0gdxXaQpjqkyBKVvz6O0zZ3iJNYXDr9i_69Q4xlXas9kL8VlCNbfN8RSrktMLlIAVpm7fAZl2zGXPYhOu6IPeXg6F0ZypxQ"
//            ["expires_in"] => int(7200)
//            ["refresh_token"] => string(107) "vgB5n-5tOraPjCklH1z31VI1PYWKF6qXP3igSz19wi8wN6edAg7uSG_7p59UgYEkYT9zagTiDO2R6Wz8dHlXXPfPTiW4HJtTyzU2TWf5x_I"
//            ["scope"] => string(28) "snsapi_base,snsapi_userinfo,"
//}
//        第四步：拉取用户信息(需scope为 snsapi_userinfo)
        $urlll = "https://api.weixin.qq.com/sns/userinfo?access_token=".$results["access_token"]."&openid=".$results["openid"]."&lang=zh_CN ";
        $data =  file_get_contents($urlll);
        $result_re = json_decode($data, true);
//        dump($result_re);
//        array(9) {
//            ["openid"] => string(28) "ofqgOwjr3aCvUqEgZoMVEGcPkowU"
//            ["nickname"] => string(9) "茹鉴！"
//            ["sex"] => int(1)
//            ["language"] => string(5) "zh_CN"
//            ["city"] => string(6) "宜宾"
//            ["province"] => string(6) "四川"
//            ["country"] => string(6) "中国"
//            ["headimgurl"] => string(116) "http://wx.qlogo.cn/mmopen/ajNVdqHZLLCp0UOjLLWlZ0rSN9vj0WsE3KmHYibZVYwXTCx3df5XuTPY4h8wPR3Dbiaajwg5Th6OGBlkjOrFALIQ/0"
//            ["privilege"] => array(0) {
//            }
            $data = [];
            $data['openid'] =  $result_re['openid'];
            $data['WeChat'] =  $result_re['nickname'];  //微信昵称
            $data['weixin_header'] = $result_re['headimgurl'];
            $data['weixin_sex'] = $result_re['sex'];
            $data['city'] = $result_re['country'].$result_re['province'].$result_re['city'];
            $login = Db::table('user')->where('opendid',$data['openid'])->find();
            if($login == null){        //根据openid来做查找，此微信是否绑定原有的账户，没有绑定则跳转页面进行绑定
                Session::set('openid',$result_re['openid']);
                Session::set('nickname',$result_re['nickname']);
                Session::set('headimgurl',$result_re['headimgurl']);
                Session::set('sex',$result_re['sex']);
                Session::set('city',$result_re['country'].$result_re['province'].$result_re['city']);
                $this->redirect('Index/phone');
            }else{//当账户已绑定并注册
                Cookie::set("user",$login["username"]);
                Cookie::set("head_img",$login["weixin_header"]);
                Cookie::set("user_id",$login["id"]);
                $this->success("登录成功","Index/index");
            }
    }
}